package com.joysuch.wwyt.licence.util;

import com.joysuch.wwyt.licence.constant.LicenceStateEnum;
import com.joysuch.wwyt.licence.exception.LicenceException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件工具类FileUtils
 * @author jialei25
 * @date 2021/2/19
 */
public class FileUtils {

    /**
     * 默认允许上传的文件类型
     */
    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            //图片
            "bmp", "gif", "jpg", "jpeg", "png",
            //word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx",
            "html", "htm", "txt",
            //压缩文件
            "rar", "zip", "gz", "bz2",
            //pdf
            "pdf"
    };

    /**
     * 默认允许上传的文件类型
     */
    public static final String[] EXCEL_ALLOWED_EXTENSION = {
            //excel
            "xls", "xlsx"
    };

    /**
     * 是否允许文件上传
     *
     * @param file             上传的文件
     * @param allowedExtension 文件类型  null 表示允许所有
     * @param maxSize          最大大小 字节为单位 -1表示不限制
     * @throws LicenceException
     */
    public static void assertAllowed(MultipartFile file, String[] allowedExtension, long maxSize)
            throws LicenceException {
        if (file == null) {
            throw new LicenceException(LicenceStateEnum.FILE_DOES_NOT_EXIST.getValue(), LicenceStateEnum.FILE_DOES_NOT_EXIST.getDesc());
        }
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            throw new LicenceException(LicenceStateEnum.ILLEGAL_FILE.getValue(), LicenceStateEnum.ILLEGAL_FILE.getDesc());
        }

        long size = file.getSize();
        if (maxSize != -1 && size > maxSize) {
            throw new LicenceException(LicenceStateEnum.FILE_TOO_LARGE.getValue(), LicenceStateEnum.FILE_TOO_LARGE.getDesc() + org.apache.commons.io.FileUtils.byteCountToDisplaySize(maxSize));
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }
}
